using System;
using System.Collections.Generic;
using System.Windows.Forms;
using smartBrowser.GUI;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
using smartBrowser.Util;
using XPExplorerBar;
using System.Drawing;

namespace smartBrowser.Task
{
    class SimiliciousTask : Task
    {                    
        public SimiliciousTask(WebSite webSite, TabPageForm form)
            : base(webSite, form)
        {
        }

        protected override void Execute()
        {
            AddExpando(FillExpando(ExpressiveWords()));
            FireCompleteEvent();
        }


        private List<string> ExpressiveWords()
        {
            List<string> links = new List<string>();

            Uri uri = new Uri("http://similicio.us/search.php?url=" + this.webSite.Url.Host + "&submit=find+similar");

            string pageSource = smartBrowser.Util.WebPageFetcher.FecthPage(uri);

            if (pageSource != null && !pageSource.Equals(""))
            {
                String expression = "<a href = http://(.*?)>(.*?)<br> ";

                Regex regex = new Regex(expression);

                MatchCollection matches = regex.Matches(pageSource);

                foreach (Match match in matches)
                {
                    links.Add(match.Groups[1].Value);
                }

                return links.GetRange(0, Math.Min(links.Count, 10));
            }
            return links;
        }


        private Expando FillExpando(List<string> links)
        {
            Expando expando = new Expando();
            expando.Text = "Sites semelhantes";
            expando.Name = "SimilarSites";

            int top = 28;

            foreach (string link in links)
            {
                double pageRank = GetPageRank(link) / 2.0;

                XPExplorerBar.TaskItem taskItem = new XPExplorerBar.TaskItem();
                taskItem.Text = link;
                taskItem.Tag = link;
                taskItem.Click += new EventHandler(taskItem_Click);
                taskItem.Location = new System.Drawing.Point(4, top);
                taskItem.Image = global::smartBrowser.Properties.Resources.text_html;

                int i;
                for (i = 1; i <= pageRank; i++)
                {
                    Label label = new Label();
                    label.Image = Image.FromFile(Path.Combine(Application.StartupPath, "star-small.png"));
                    label.Left = i * 12 + 150;
                    label.Top = top;
                    label.Width = 12;
                    label.Height = 12;
                    expando.Items.Add(label);
                }

                if (pageRank - (int)pageRank >= 0.3)
                {
                    Label label = new Label();
                    label.Image = Image.FromFile(Path.Combine(Application.StartupPath, "star-half-small.png"));
                    label.Left = i * 12 + 150;
                    label.Top = top;
                    label.Width = 6;
                    label.Height = 12;
                    
                    expando.Items.Add(label);
                }

                expando.Items.Add(taskItem);
                top += 22;
            }

            expando.Size = new System.Drawing.Size(expando.Size.Width, top);
            return expando;
        }

        int GetPageRank(string link)
        {
            Regex expression = new Regex(".*imgRank\\[(\\d+)\\].*");

            string pageSource = smartBrowser.Util.WebPageFetcher.FecthPage(new Uri("http://www.checkpagerank.com/jscripts/js_pagerank.php?domain=" + link));
            return Convert.ToInt32(expression.Match(pageSource).Groups[1].Value);
        }

        void taskItem_Click(object sender, EventArgs e)
        {
            SmartBrowser.Instance.OpenNewTabAt(((TaskItem)sender).Tag.ToString());
        }

        private delegate void AddExpandoDelegate(Expando expando);
        private void AddExpando(Expando expando)
        {
            if (this.form.TaskPane.InvokeRequired)
            {
                AddExpandoDelegate del = new AddExpandoDelegate(AddExpando);
                this.form.TaskPane.Invoke(del, new object[] { expando });
            }
            else
            {
                foreach (Expando exp in this.form.TaskPane.Expandos)
                {
                    if (exp.Name == expando.Name)
                    {
                        this.form.TaskPane.Expandos.Remove(exp);
                        break;
                    }
                }

                if (expando.Items.Count > 0)
                    this.form.TaskPane.Expandos.Add(expando);
            }
        }
    }
}
